var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var mime = require('mime');
var mysql = require('mysql');
var tempUser = {};

http.createServer(function (req, res) {
	var urlDecoded, restPath, replyObject;
	
	urlDecoded = url.parse(req.url, true);
	restPath = urlDecoded.pathname.split('/');
	console.log(urlDecoded);
	console.log('Num Args: ' + restPath.length);
	console.log(urlDecoded.pathname.replace(/\//g, "\\"));

	switch(restPath[1]) {
		case 'auth':
			switch(restPath[2]) {
				case 'login':
					//console.log('replyObject = doLogin(' + restPath[3] + ', ' + restPath[4] + ')');
					doLogin(restPath[3], restPath[4]);
					break;
			}
			break;
		case '':
		case 'index.html':
			try {
				res.writeHead(200, {'Content-Type': 'text/html'});
				var fileStream = fs.createReadStream("..//httpdocs//index.html");
				fileStream.pipe(res);
			}
			catch(ee) {
				res.writeHead(404, {'Content-Type': 'text/html'});
				res.end();
				//returnError();
			}
			break;			
		case 'mock':
			res.writeHead(200, {'Content-Type': 'application/json'});
			mockResults = {
							status: {code: 0, message: "OK", timeStamp: "2012-07-20 15:00:00" },
							tables: [ 
							          { name: "table_name", 
									  	lastUpdate: "2012-07-20 15:00:00",
										keyField: "id",
							            rows: [ ]
									  }
									]
										 
			}
			var rone = {id: 1, name: "fred", email: "fred@fish.com"};
			var rtwo = {id: 2, name: "jason", email: "jvoorhees@bloodydisgusting.com"};
			mockResults.tables[0].rows = new Array();
			mockResults.tables[0].rows.push({id: 1, name: "fred", email: "fred@fish.com"});
			mockResults.tables[0].rows.push(rtwo);
			console.log(JSON.stringify(mockResults));
			res.write(JSON.stringify(mockResults));
			res.end();				
			break;
			
		default:
			//console.log(urlDecoded);

			var mimeType;				
			mimeType = mime.lookup("..//httpdocs" + urlDecoded.pathname);
			console.log("mime type: " + mimeType + "\n");
			if (fs.existsSync("..//httpdocs" + urlDecoded.pathname)) {			
				res.writeHead(200, {'Content-Type': mimeType});
				var fileStream = fs.createReadStream("..//httpdocs" + urlDecoded.pathname);
				fileStream.pipe(res);
			}
			else {
				res.writeHead(404, {'Content-Type': 'text/html'});
				res.end();
				//returnError();
				break;
			}
			break;
	}

	function doLogin(user, pass) {	
		var connection, querySQL, args, query;
		connection = mysql.createConnection({host: 'localhost', user : 'root', password : '', database: 'titanium'});
		querySQL = "SELECT * FROM users WHERE username = ? AND userpass = ? LIMIT 1;";
		query = connection.query(querySQL, [user, pass], function(err, rows, fields)	 {

		if (err) {
			console.log(err);
			tempUser = { error: 1 };
		}
		else {
			console.log(query.sql)
			if (rows.length > 0) {
				tempUser = { "error": 0, "userName": user, "md5Pass": pass,"firstName": rows[0].first_name, "lastName": rows[0].last_name, "userGroups": [5,3], "userLevel": rows[0].user_level };
				console.log(tempUser);
			}
			else {
				tempUser = { error: 1 };
				console.log(tempUser);
			}
		}
		console.log(query.sql)
		res.writeHead(200, {'Content-Type': 'application/json'});
		//console.log(JSON.stringify(replyObject));
		res.write(JSON.stringify(tempUser));
		res.end();					
						
	});
};

		
}).listen(8181, 'tardis.localhost');

console.log('Server running at http://tardis.localhost:8181/');


